import Vue from 'vue'
import Router from 'vue-router'
import login from '@/views/login'
import search from '@/views/search'
import home from '@/views/home'
import myDay from '@/views/myday'
import todolist from '@/views/checklist'
import axios from 'axios'
import VueCookie from 'vue-cookie'
import store from '@/store'

Vue.use(Router)

const router = new Router({
  routes: [
    {
      // 重定向
      path: '/',
      redirect: '/myday'
    },
    {
      path: '/login',
      name: 'login',
      component: login
    },
    {
      path: '/',
      component: home,
      children: [
        {
          path: 'myday',
          name: 'myday',
          component: myDay
        },
        {
          path: 'search',
          name: 'search',
          component: search
        },
        {
          path: '/list/:id',
          component: todolist
        }
      ],
      // 在当前路由中设置路由守卫
      beforeEnter: (to, from, next) => {
        // 获取islogin
        let token = VueCookie.get('token')
        if (!token) {
          // 没有登录则跳转到login页面
          next('/login')
          // 否则正常跳转
        } else {
          // 每次刷新重新获取用户信息
          router.app.$options.store.dispatch('getUser')
          next()
        }
      }
    }
  ]
});

// 全局路由守卫
// router.beforeEach((to, from, next) => {
//   let token = VueCookie.get('token')
//   if (to.name === 'login') {
//     next()
//   } else {
//     if (!token) {
//       next('/login')
//     } else {
//       // 否则正常跳转
//       // 每次刷新重新获取用户信息
//       router.app.$options.store.dispatch('getUser')
//       next()
//     }
//   }
// })


export default router
